package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.OrderActor;
import com.qianniu.napi.admin.service.akka.UserActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.EncryptUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author chenxuebin
 * @since 2020-08-11
 */
@Controller
public class VisitLogController {

    private static final Logger logger = LoggerFactory.getLogger(VisitLogController.class);

    @Autowired
    private IVisitLogService visitlogService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IUserService userService;
    @Autowired
    private INewsService newsService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IShareService shareService;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private IGoodsQunzfService goodsQunzfService;

    @RequestMapping("/api/visitlog/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = visitlogService.selectPage(page, new EntityWrapper<VisitLog>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    //页面访问日志
    //核心：记录页面打开进入|离开记录
    @RequestMapping("/api/visitlog/add")
    @ResponseBody
    public Jinfo visitlogAdd(VisitLog visitlog,
                             @RequestParam(value = "ori", required = false) String ori,
                             @RequestParam(value = "ma", required = false) String ma
    ) {
        Jinfo info = new Jinfo();
        // 字段校验
        logger.debug("----------------------------------------------------------------------------ori=" + ori);
        logger.debug("----------------------------------------------------------------------------ma=" + ma);

        String path = ObjectUtil.sortQuery(visitlog.getPath());
        Map<String, String> pathmap = ObjectUtil.sortQueryMap(visitlog.getPath());
        if (pathmap != null && Strings.isNullOrEmpty(ma) && pathmap.containsKey("ma")) {
            ma = pathmap.get("ma");
        }
        if (Strings.isNullOrEmpty(ori) && pathmap != null && pathmap.containsKey("ori")) {
            ori = pathmap.get("ori");
        }
        logger.debug("----------------------------------------------------------------------------path=" + path);

        String pathguid = EncryptUtil.md5(path);
        visitlog.setPath(path);
        visitlog.setPathguid(pathguid);

        visitlog.setPage(path.indexOf("?")>0?path.substring(0,path.indexOf("?")):path);
        logger.debug("---------------------------------------------------------------------------visitlog.path=" + visitlog.getPath());

        visitlog.setCreateday(DateUtil.getToday());
        visitlog.setCreatetime(new Date());
        visitlog.setUid(ObjectUtil.getUid());
        visitlog.setMid(ObjectUtil.getMid());
        visitlog.setMpid(ObjectUtil.getMpid());
        visitlog.setGuid(ObjectUtil.getGuid());
        visitlog.setShareday(DateUtil.getToday());
        Long ywid = null;

        if (!Strings.isNullOrEmpty(ma)) {
            ori = ma;// 海报扫码优先级高
            visitlog.setOri(ma);
//            String ma[scene]= uid + "_" + Constants.PAGE_MAP.get(page) + "_Q_" + ywid;
            Long uid = null;
            String[] oris = ori.split("_");
            if (oris.length == 4) {
                try {
                    uid = Long.valueOf(oris[0]);
                    ywid = Long.valueOf(oris[3]);
                } catch (Exception e) {
                    logger.error("======shareopenAdd parse uid error", e);
                }
            }
            visitlog.setZuid(uid);
            User zuser = userService.selectById(uid);

            if (zuser != null) {
                visitlog.setZguid(zuser.getGuid());
            }

        } else if (!Strings.isNullOrEmpty(ori)) {
            visitlog.setOri(ori);
            visitlog.setZguid(ori.split("_")[0]);
            String[] oris = ori.split("_");
            ywid = Strings.isNullOrEmpty(oris[3]) ? null : Long.valueOf(oris[3]);

            User zuser = redisService.getUserByGuid(visitlog.getZguid());
            if (zuser != null) {
                visitlog.setZuid(zuser.getId());
            }
            User user = redisService.getUserByGuid(visitlog.getGuid());
            if (user != null) {
                visitlog.setOpenid(user.getOpenid());
            }

        }
        visitlog.setYwid(ywid);

        Long sid = null;
        Long leagueid = null;

        if (ywid != null) {
            Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().setSqlSelect("id,sharenum,sid,leagueid").eq("id", ywid));
            CouponTpl ctpl = couponTplService.selectOne(new EntityWrapper<CouponTpl>().setSqlSelect("id,sid,leagueid").eq("id", ywid));
            News news = newsService.selectOne(new EntityWrapper<News>().setSqlSelect("id,sid,leagueid").eq("id", ywid));

            if (goods != null) {
                sid = goods.getSid();
                leagueid = goods.getLeagueid();
            } else if (ctpl != null) {
                sid = ctpl.getSid();
                leagueid = ctpl.getLeagueid();
            } else if (news != null) {
                sid = news.getSid();
                leagueid = news.getLeagueid();
            }
        }

        if (sid != null && sid.intValue() == 0) sid = null;
        visitlog.setSid(sid);
        visitlog.setLeagueid(leagueid);

        // 转发必须带参数，如无[ts=timestamp]
        Share share = shareService.selectOne(new EntityWrapper<Share>().eq("pathguid", pathguid));

        if (share != null) {

            visitlog.setShareid(share.getId());
            VisitLog nshareopen = new VisitLog();
            nshareopen.setShareid(share.getId());//========1、更新同分享路径shareid========
            visitlog.setGroupid(share.getGroupid());

            visitlogService.update(nshareopen, new EntityWrapper<VisitLog>().eq("pathguid", pathguid));
            share.updateById();

            visitlog.setZguid(share.getGuid());
            visitlog.setZuid(share.getUid());
        }


        if (visitlog.getIotype() == -1) {
            VisitLog visit = visitlogService.selectOne(new EntityWrapper<VisitLog>()
                    .eq("md5", visitlog.getMd5()));
            if (visit != null) {
                long timelong = (visitlog.getVisitstamp() - visit.getVisitstamp()) / 1000;
                visitlog.setTimelong(timelong);
            }
        }

        visitlog.insert();

        return info;
    }


    @RequestMapping("/api/visitlog/detail")
    @ResponseBody
    public Jinfo getVisitLogDetailById(@RequestParam("token") String token,
                                       @RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        VisitLog visitlog = visitlogService.selectById(id);
        info.setInfo(visitlog);
        return info;
    }
}
